/**
 * API请求工具
 */

// 基础API地址
const API_BASE = '/api'

/**
 * 获取认证头
 */
function getAuthHeaders() {
  const token = localStorage.getItem('token')
  if (token) {
    return {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    }
  }
  return {
    'Content-Type': 'application/json'
  }
}

/**
 * 通用GET请求
 */
export async function apiGet(url, options = {}) {
  try {
    const response = await fetch(`${API_BASE}${url}`, {
      method: 'GET',
      headers: getAuthHeaders(),
      ...options
    })

    if (!response.ok) {
      if (response.status === 401) {
        // Token过期，跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        location.href = '/login'
        throw new Error('认证失败，请重新登录')
      }
      throw new Error(`请求失败: ${response.status}`)
    }

    return await response.json()
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

/**
 * 通用POST请求
 */
export async function apiPost(url, data = {}, options = {}) {
  try {
    const response = await fetch(`${API_BASE}${url}`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
      ...options
    })

    if (!response.ok) {
      if (response.status === 401) {
        // Token过期，跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        location.href = '/login'
        throw new Error('认证失败，请重新登录')
      }
      throw new Error(`请求失败: ${response.status}`)
    }

    // 如果响应是204 No Content，直接返回成功对象而不尝试解析JSON
    if (response.status === 204) {
      return { status: 204, success: true }
    }

    // 检查响应内容长度
    const contentLength = response.headers.get('content-length')
    if (contentLength === '0' || !contentLength) {
      return { status: response.status, success: true }
    }

    return await response.json()
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

/**
 * 通用PUT请求
 */
export async function apiPut(url, data = {}, options = {}) {
  try {
    const response = await fetch(`${API_BASE}${url}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
      ...options
    })

    if (!response.ok) {
      if (response.status === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        location.href = '/login'
        throw new Error('认证失败，请重新登录')
      }
      throw new Error(`请求失败: ${response.status}`)
    }

    // 如果响应是204 No Content，直接返回成功对象而不尝试解析JSON
    if (response.status === 204) {
      return { status: 204, success: true }
    }

    // 检查响应内容长度
    const contentLength = response.headers.get('content-length')
    if (contentLength === '0' || !contentLength) {
      return { status: response.status, success: true }
    }

    return await response.json()
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

/**
 * 通用DELETE请求
 */
export async function apiDelete(url, options = {}) {
  try {
    const response = await fetch(`${API_BASE}${url}`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
      ...options
    })

    if (!response.ok) {
      if (response.status === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        location.href = '/login'
        throw new Error('认证失败，请重新登录')
      }
      throw new Error(`请求失败: ${response.status}`)
    }

    // 如果响应是204 No Content，直接返回成功对象而不尝试解析JSON
    if (response.status === 204) {
      return { status: 204, success: true }
    }

    // 检查响应内容长度
    const contentLength = response.headers.get('content-length')
    if (contentLength === '0' || !contentLength) {
      return { status: response.status, success: true }
    }

    return await response.json()
  } catch (error) {
    console.error('API请求错误:', error)
    throw error
  }
}

/**
 * 检查是否已登录
 */
export function isLoggedIn() {
  return !!localStorage.getItem('token')
}

/**
 * 获取当前用户信息
 */
export function getCurrentUser() {
  return {
    id: localStorage.getItem('userId') ? parseInt(localStorage.getItem('userId')) : null,
    username: localStorage.getItem('username') || '',
    name: localStorage.getItem('name') || '',
    avatarUrl: localStorage.getItem('avatarUrl') || '',
    token: localStorage.getItem('token') || ''
  }
}

/**
 * 退出登录
 */
export function logout() {
  localStorage.removeItem('token')
  localStorage.removeItem('userId')
  localStorage.removeItem('username')
  localStorage.removeItem('name')
  localStorage.removeItem('avatarUrl')
  location.href = '/login'
}

/**
 * 采购退货单API
 */
export const returnOrderApi = {
  // 分页查询退货单
  getPage: (params) => apiGet(`/purchase-return-order/page?${new URLSearchParams(params).toString()}`),

  // 创建退货单
  create: (data) => apiPost('/purchase-return-order/create', data),

  // 获取退货单详情
  getDetail: (id) => apiGet(`/purchase-return-order/${id}`),

  // 提交审核
  submitAudit: (id) => apiPost(`/purchase-return-order/submit/${id}`),

  // 审核退货单（后端为 /purchase-return-order-audit/audit/{returnOrderId} 并接收查询参数）
  audit: (data) => {
    const { returnOrderId, auditorId, auditOpinion, auditResult } = data || {}
    const qs = new URLSearchParams({
      auditorId: auditorId ?? '',
      auditOpinion: auditOpinion ?? '',
      auditResult: auditResult ?? ''
    }).toString()
    return apiPost(`/purchase-return-order-audit/audit/${returnOrderId}?${qs}`, {})
  },

  // 获取采购订单列表
  getPurchaseOrders: () => apiGet('/purchase-order/list'),

  // 获取采购订单商品明细
  getOrderItems: (orderId) => apiGet(`/purchase-order/items/${orderId}`),

  // 获取审核记录
  getAuditRecord: (returnOrderId) => apiGet(`/purchase-return-order-audit/record/${returnOrderId}`)
}
